package com.wisdytech.ccdserver.common.utils;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @author sunjinxin
 * @date 2024/3/28
 */
public class AmazonS3Utils {
    static AmazonS3 amazonS3Client;

    /**
     * 初始化amazonS3Client
     */
    public static void initS3Client(String access_key,String secret_key,String endpoint) {
        AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);   //创建AWS凭证
        ClientConfiguration connconfig = new ClientConfiguration();            //初始化客户端config
        connconfig.setProtocol(Protocol.HTTP);                                //设置mos 请求协议为http

        //使用AWS凭证和clientConfiguration初始化AmazonS3Client客户端
//        amazonS3Client = new AmazonS3Client(credentials, connconfig);
//        amazonS3Client.setEndpoint(endpoint);                               ////设置mos对象服务接口地址
//        amazonS3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).disableChunkedEncoding().build());

        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, Regions.CN_NORTH_1.getName());

        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(credentials);
        amazonS3Client= AmazonS3Client.builder().withEndpointConfiguration(endpointConfiguration)
                .withClientConfiguration(connconfig)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();


    }

    public static String uploadUrl(String bucket_name,String object_key) throws Exception {
        // url一个小时后失效
        java.util.Date expiration = new java.util.Date();
        long expTimeMillis = expiration.getTime();
        expTimeMillis += 1000 * 60 * 60;
        expiration.setTime(expTimeMillis);

        // 生成临时上传对象url
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                bucket_name, object_key).withMethod(HttpMethod.GET)
                .withExpiration(expiration);
        URL url = amazonS3Client
                .generatePresignedUrl(generatePresignedUrlRequest);

        return url.toString();
    }

    public static byte[] downloadImage(String bucket_name, String object_key) throws Exception {
        // url一个小时后失效
        //下载对象
        S3Object object = amazonS3Client.getObject(bucket_name, object_key);
        //获取对象流
        S3ObjectInputStream objectContent = object.getObjectContent();

        byte[] byteBuffer = null;
        ByteArrayOutputStream outByte = new ByteArrayOutputStream();
        byte[] tmpByte = new byte[1024];
        int len = 0;
        while ((len = objectContent.read(tmpByte)) != -1) {
            outByte.write(tmpByte, 0, len);
        }
        byteBuffer = outByte.toByteArray();
        return byteBuffer;
    }

    /**
     * 对应MOS JAVA SDK文档4.5.2章节   流式下载
     *
     * @throws Exception
     */
    public static void downFile(String bucket_name,String object_key,String rootUrl,String filePath,String fileName) throws Exception {
        //下载对象
        S3Object object = amazonS3Client.getObject(bucket_name, object_key);
        //获取对象流
        S3ObjectInputStream objectContent = object.getObjectContent();
        //初始化文件输出流
        filePath = rootUrl+filePath;
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdirs();
        }

        FileOutputStream fileOutputStream = new FileOutputStream(filePath+"/"+fileName);

        byte[] readbuf = new byte[1024];
        int read_len = 0;
        while ((read_len = objectContent.read(readbuf)) > 0) {
            //对象下载字节写入文件输出流
            fileOutputStream.write(readbuf, 0, read_len);
        }
        //关闭流
        objectContent.close();
        fileOutputStream.close();
    }

    /**
     * 关闭amazonS3Client
     */
    public static void close() {
        amazonS3Client.shutdown();            //关闭客户端
    }
}
